package cn.lin.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * 敏感词汇=过滤
 */
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
    private static List<String> list = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            //加载IO流配置
            // 先获取文件真实路径
            ServletContext servletContext = filterConfig.getServletContext();
            String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt");
            //读取文件
            BufferedReader br = new BufferedReader(new FileReader(realPath));

            //读取文件了
            String line = null;
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            br.close();

            System.out.println(list);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //创建代理对象,增强getParamter方法
        ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(servletRequest.getServletContext().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //增强getParameter方法
                if (method.getName().equals("getParameter")) {
                    //增强返回值
                    //获取返回值
                    String value = (String) method.invoke(servletRequest, args);

                    if (value != null) {
                        for (String s : list) {
                            if (value.contains(s)) {
                                String str = "";
                                for (int i = 0; i < s.length(); i++) {
                                    str += "*";
                                }
                                //包含有敏感字符
                                value = value.replaceAll(s, str);
                            }
                        }
                    }
                    return value;
                }
                return method.invoke(servletRequest, args);
            }
        });


        //放行
        filterChain.doFilter(proxy_req, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
